<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getStudentList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getStudentList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >批量导入学生</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="studentlist" border stripe>
        <!-- 展开区域 -->
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form
              label-position="right"
              class="demo-table-expand"
              label-width="100px"
              label-suffix=":"
              inline
            >
              <el-form-item label="身份证号">
                <span>{{ props.row.idcardnumber }}</span>
              </el-form-item>
              <el-form-item label="家庭住址">
                <span>{{ props.row.address }}</span>
              </el-form-item>
              <el-form-item label="家长电话">
                <span>{{ props.row.family_phone }}</span>
              </el-form-item>
              <el-form-item label="家庭关系">
                <span>{{ props.row.relations }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="性别">
          <template slot-scope="scope">
            {{ scope.row.sex ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column label="学院">
          <template slot-scope="scope">
            {{ scope.row.cls.school.name }}
          </template>
        </el-table-column>
        <el-table-column label="班级">
          <template slot-scope="scope">
            {{ scope.row.cls.name }}
          </template>
        </el-table-column>
        <el-table-column label="市场部" prop="market"></el-table-column>
        <el-table-column label="手机号" prop="phone"></el-table-column>
        <el-table-column label="宿舍号-床位">
          <template slot-scope="scope">
            {{ scope.row.dormnumber }}-{{ scope.row.bednumber }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="批量导入学生信息"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="学院" prop="school">
          <el-select @change="handleCollegeChange" v-model="addForm.school" placeholder="请选择学院">
            <el-option
              v-for="item in collegesOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="cls">
          <el-select v-model="addForm.cls" placeholder="请选择班级">
            <el-option
              v-for="item in clsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="uploaditem" label="Excel文件" prop="excel">
          <el-upload
            class="upload-demo"
            name="stufile"
            drag
            :headers="header"
            :data="addForm"
            action="/api/students/uploadexcel"
            :auto-upload="false"
            ref="uploadFile"
            :on-success="uploadSuccess"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
          <el-link href="http://127.0.0.1:8000/api/students/download"
          target="_blank" type="primary" icon="el-icon-download">下载excel模板</el-link>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getStudents, downloadTemp,removeStudents,searchByName } from '@/api/students'
import { getHeader } from '@/utils/login'
import {getColleges} from '../../api/department'
import {getClassByCollegeId} from '../../api/class'
export default {
  data() {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      collegesOptions: [],
      clsOptions: [],
      header: {},
      studentlist: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        school: '',
        cls: '',
      },
      // 添加表单的验证规则对象
      addFormRules: {
        school: [{ required: true, message: '请选择学院', trigger: 'blur' }],
        cls: [{ required: true, message: '请选择班级', trigger: 'blur' }],
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},

      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色Id值
      selectedRoleId: '',
    }
  },
  created() {
    this.header = getHeader()
    this.getStudentList()
    this.getCollegesOptions()
  },
  methods: {
    //获取所有的学院信息
    async getCollegesOptions(){
      const result = await getColleges()
      this.collegesOptions=[]
      if(result){
        result.forEach(item => {
          this.collegesOptions.push({
            value:item.id,
            label:item.name
          })
        });
      }
    },
    //处理学院改变
    async handleCollegeChange(val){
      const result=await getClassByCollegeId(val)
      this.clsOptions=[]
      if(!result) return 
      result.forEach(item => {
        this.clsOptions.push({
          label:item.name,
          value:item.id
        })
      });

    },
    async getStudentList() {
      const result = await getStudents(this.queryInfo)
      this.studentlist = result.data
      this.total = result.count //数据总条数
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getStudentList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getStudentList()
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return

        this.$refs.uploadFile.submit()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      // console.log(id)
      const { data: res } = await this.$http.get('users/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }

      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }

        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getStudentList()
        // 提示修改成功
        this.$message.success('更新用户信息成功！')
      })
    },
    // 根据Id删除对应的用户信息
    async removeUserById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const result = await removeStudents(id)
      if (result != undefined) {
        this.$message.success('删除用户成功！')
        this.getStudentList()
      }
    },


    uploadSuccess(response, file, fileList) {
      if(response.error){
        this.$message.warning('已存在身份证号相同的学生！详情请查看控制台~')
      }else{
        this.$message.success('导入成功~')
        this.addDialogClosed()
        this.getStudentList()
      }
    },
    download() {
       downloadTemp()
    },
  },
}
</script>

<style  scoped>
.el-select {
  width: 100%;
}
</style>
